import { NextResponse } from "next/server";

import { getSignature } from "@/app/utils/signature";
import { apiClient } from "@/app/utils/client";

const GET_PPT_URL_INTERVAL = 4000; // 获取ppt轮询间隔5秒

const timeout = 10 * 60 * 1000; // 最大超时时间10分钟
let startTime = Date.now();

async function getPPTUrl(timestamp: number, signature: string, sid: string) {
  console.log(Date.now(), startTime);
  if (Date.now() - startTime > timeout) {
    throw new Error("轮询超时");
  }

  //获取ppt
  const resp = await apiClient.checkProgress(
    timestamp.toString(),
    signature,
    sid,
  );

  if (resp.data.pptStatus === "done") {
    return resp;
  } else {
    await new Promise((resolve) => setTimeout(resolve, GET_PPT_URL_INTERVAL));

    return await getPPTUrl(timestamp, signature, sid); // 递归调用
  }
}

export async function POST(request: Request) {
  console.log("POST");
  const body = await request.json();

  const timestamp: number = Math.floor(Date.now() / 1000);

  const signature: string = getSignature(timestamp);

  const resp = await apiClient.create(
    timestamp.toString(),
    signature,
    body.content,
    body.templateId,
  );
  // const resp =
  // {
  //   flag: true,
  //   code: 0,
  //   desc: '成功',
  //   count: null,
  //   data: {
  //     sid: '02dba9879f7d421a84f1a4533c5dfcd5',
  //     coverImgSrc: 'https://bjcdn.openstorage.cn/xinghuo-privatedata/zhiwen/2025-03-21/2f9037f3-4792-44fd-add9-3168f5c63fce/68ad4d9ae29b4b9aa1f88f732b51e4d3.png',
  //     title: '滕王阁序文学鉴赏',
  //     subTitle: '从基础到挑战的深度解析'
  //   },
  //   sid: null
  // }

  console.log("apiClient.create", resp);

  //获取ppt
  startTime = Date.now();
  const ppt = await getPPTUrl(timestamp, signature, resp.data.sid);

  ppt.data.coverImgSrc = resp.data.coverImgSrc;

  console.log("getPPTUrl", ppt);

  // const ppt = {
  //   flag: true,
  //   code: 0,
  //   desc: "成功",
  //   count: null,
  //   data: {
  //     pptStatus: "done",
  //     aiImageStatus: "done",
  //     cardNoteStatus: "done",
  //     pptUrl:
  //       "https://bjcdn.openstorage.cn/xinghuo-privatedata/zhiwen/2025-03-21/c9f4b6fa-c4e4-446a-b1e2-610afa8b3c9a/4e225241616346a7a2881fc101c1bc6b.pptx",
  //     errMsg: null,
  //     totalPages: 31,
  //     donePages: 31,
  //     coverImgSrc:
  //       "https://bjcdn.openstorage.cn/xinghuo-privatedata/zhiwen/2025-03-21/f161b07b-4a17-42b8-9dfd-d7b6f787e768/ebf6464b49e84c2fad60d73cf1fdde1b.png",
  //   },
  //   sid: null,
  // };

  return NextResponse.json(ppt.data, { status: 200 });
}
